// 异步操作
import { Route } from "@/api";
import { Role } from "@/api";

// 加载路由列表 
let route_list = async (context) => {
    let { status, msg, data } = await Route.all({ type: 'flat' });
    if (status) {
        context.commit('ROUTE_LIST', data);
    }
    return { status, msg };
}

// 更新路由
let edit_route = async (context, payload) => {
    let { status, msg } = await Route.update(payload.route_id, payload);
    if (status) {
        context.commit('EDIT_ROUTE', payload);
    }
    return { status, msg }
}

// 添加路由
let add_route = async (context, playload) => {
    let { status, msg, data } = await Route.add(playload);
    if (status) {
        context.commit('ADD_ROUTE', { ...data, ...playload });
    }
    // 尽量在组件中实现跳转。弹窗等功能；return出去的是Promise对象
    return { status, msg }
}

// 删除路由
let remove_route = async (context, payload) => {
    let { route_id, permission_id } = payload;
    let res = context.state.routes.some(item => item.parent_id === route_id);
    if (!res) {
        let { status, msg } = await Route.remove(route_id, { permission_id });
        if (status) {
            // 通过传的id找索引
            context.commit('REMOVE_ROUTE', route_id);
        }
        return { status, msg }
    } else {
        alert("存在子级路由!");
    }
}

// 根据角色id，获取角色的路由权限
let route_power = async (context, payload) => {
    let { status, msg, data } = await Role.route_power({ role_id: payload, type: 'flat' });
    let selectedNodes = [];
    data.forEach(function (item) {
        selectedNodes.push(item.permission_id);
    });
    if (status) {
        context.commit('ROUTE_POWER', selectedNodes);
    }
    return { status, msg, selectedNodes };
}

//  配置角色--路由权限
let set_route_power = async (context, payload) => {
    let { status, msg, data } = await Role.set_route_power(payload);
    return { status, msg, data };
}

export default {
    route_list,
    edit_route,
    add_route,
    remove_route,
    route_power,
    set_route_power,
}